let we = require('../../we/index.js')
let animation = wx.createAnimation({
    duration: 1000,
    timingFunction: 'ease',
})
new class extends we.Page {
    data() {
        return {
            vo: {
                freight: '',
                status: '',//'-2init'，'-1失效',0joing','regret','prize','1open','2支付成功'
                peopleNum: 'full',
                showPrize: false,
                addressName: '',
                addressPhone: '',
                address: '',
                showWinner: false,
                winnerName: '',
                winnerAvatar: '',
                winnerTime: '',
                openPrizeBtn: '',
                prizeHandle: '',
                payHandle: '',
                member: [],
                goodsInfo: {}
            },
            po: {
                productId: '',
                joinId: '',
                addressId: ''
            }
        }
    }

    onShareAppMessage() {
        let encodeUrl = encodeURIComponent('/pages/lottery/index?joinId=' + this.data.po.joinId)
        let lotteryUrl = '/pages/index/index?target=' + encodeUrl
        return {
            title: '和好友组团拼手气，奖品免费拿～',
            path: this.data.po.joinId.length > 0 ? lotteryUrl : '/pages/index/index',
            success: (res) => {
                this.$post('/user/inviteFriend', {type: 0}).then((res)=> {
                }).catch(err=> {
                })
            }
        }
    }

    onLoad(options) {
        this.setData({
            'vo.freight': wx.getStorageSync('freight')
        })
        if (options.joinId) {   //url中有参团Id，受邀参团用户
            wx.showToast({
                title: 'jinlai',
                icon: 'none'
            })
            this.joinCollage(options.joinId)
            this.setData({
                'vo.openPrizeBtn': '点击开奖',
                'po.joinId': options.joinId
            })
        } else if (options.payId) {  //奖品列表过来
            this.getAddressInfo()
            this.collageInfo(options.payId)
        } else {       //url中没有参团Id，发起拼团/已参团用户
            let goods = JSON.parse(wx.getStorageSync('goods'))
            this.setData({
                'vo.goodsInfo': goods[options.num],
                'po.productId': options.productId
            })
            this.collageList(this.data.po.productId)
        }
    }

    //拼团消息
    collageInfo(id) {
        this.$post('/collage/info', {id}).then(res => {
            res.member.map((item, index)=> {
                if (item.isMe) {
                    this.setData({
                        'vo.goodsInfo': res.product,
                        'vo.status': 'prize',
                        'po.joinId': res._id,
                        'vo.member': res.member,
                        'vo.showPrize': false,
                        'vo.showWinner': true,
                        'vo.winnerName': item.user.nickName,
                        'vo.winnerAvatar': item.user.avatarUrl,
                        'vo.winnerTime': this.getWinnerTime(item.openPrizeTime)
                    })
                }
            })
        }).catch(err=> {
            wx.showToast({
                title: err.message,
                icon: 'none'
            })
        })
    }

    collageList(productId) {
        this.$post('/collage/list', {productId}).then(res=> {
            if (res.length === 0) { //如果今天没有参加过此商品的拼团
                this.setPageStatus(-2)
                this.setData({
                    'vo.openPrizeBtn': '发起拼团'
                })
                return
            }

            for (let item of res[0].member) {
                if (item.isMe) {
                    if (item.openPrize && !res[0].winner) { //如果参加了拼团开过奖未中奖
                        this.setPageStatus(-2)
                        this.setData({
                            'vo.openPrizeBtn': '发起拼团'
                        })
                        return
                    }
                    if (res[0].winner && res[0].status === 1 && item.openPrize) {//中奖未支付
                        this.getAddressInfo()
                        this.setData({
                            'vo.status': 'prize',
                            'po.joinId': res[0]._id,
                            'vo.member': res[0].member,
                            'vo.showPrize': false,
                            'vo.showWinner': true,
                            'vo.winnerName': item.user.nickName,
                            'vo.winnerAvatar': item.user.avatarUrl,
                            'vo.winnerTime': this.getWinnerTime(item.openPrizeTime)
                        })
                        return
                    }

                    if ((res[0].status === 1 || res[0].status === 2) && !item.openPrize) {//如果未开奖
                        this.setPageStatus(res[0].status)
                        this.setData({
                            'vo.member': res[0].member,
                            'po.joinId': res[0]._id,
                            'vo.openPrizeBtn': '点击开奖'
                        })
                        return
                    }
                    if (res[0].status === 0) {//如果拼团人数未满
                        this.setPageStatus(res[0].status)
                        this.setData({
                            'vo.member': res[0].member,
                            'po.joinId': res[0]._id,
                            'vo.openPrizeBtn': '点击开奖'
                        })
                    }
                    break
                }
            }
        }).catch(err=> {
            wx.showModal({
                title: "错误",
                content: err.message,
                showCancel: false
            })
        })
    }

    setPageStatus(status) {
        switch (status) {
            case -1:
                this.$showModal({
                    title: '提示',
                    content: '拼团超时，奖品已失效',
                    showCancel: false
                })
                break
            default:
                this.setData({
                    'vo.status': status
                })
        }
    }

    getPrizeClick() {
        this.setData({
            'vo.showPrize': false
        })
    }

    getWinnerTime(date) {
        let month = new Date(date).getMonth() + 1
        let day = new Date(date).getDate() > 9 ? new Date(date).getDate() : '0' + new Date(date).getDate()
        let hours = new Date(date).getHours() > 9 ? new Date(date).getHours() : '0' + new Date(date).getHours()
        let min = new Date(date).getMinutes() > 9 ? new Date(date).getMinutes() : '0' + new Date(date).getMinutes()
        return `${month}月${day}日 ${hours}:${min}`

    }


    //点击开奖
    openLottery() {
        if (this.data.vo.openPrizeBtn === '发起拼团') {
            this.launchCollage(this.data.po.productId)
            return
        }
        this.$post('/collage/openPrize', {id: this.data.po.joinId}).then((res)=> {
            if (res.winner) {//中奖
                this.setData({
                    'vo.status': 'prize',
                    'vo.showWinner': 'true',
                    'vo.showPrize': true
                })
                this.getAddressInfo()
            } else {
                this.setData({
                    'vo.status': 'regret'
                })
            }
            res.member.map((item, index)=> {
                if (item.isWinner) {
                    this.setData({
                        'vo.showWinner': true,
                        'vo.winnerName': item.user.nickName,
                        'vo.winnerAvatar': item.user.avatarUrl,
                        'vo.winnerTime': this.getWinnerTime(item.openPrizeTime)
                    })
                }
            })
        }).catch(err=> {
            if (err.message === '拼团人数未满！') {
                wx.showToast({
                    title: '拼团人数未满，快去邀请好友！',
                    icon: 'none'
                })
            } else {
                wx.showModal({
                    title: "错误",
                    content: err.message,
                    showCancel: false
                })
            }

        })
    }

    //发起拼团
    launchCollage(productId) {
        this.$post('/collage/launch', {productId}).then(data => {
            if (data.code) {
                return wx.showToast({
                    title: data.reason,
                    icon: 'none'
                })
            }
            this.setData({
                'po.joinId': data.id,
                'vo.openPrizeBtn': '点击开奖',
                'vo.member': data.collage.member
            })
            this.setPageStatus(data.collage.status)
        }).catch(err=> {
            wx.showModal({
                title: "错误",
                content: err.message,
                showCancel: false
            })
        })
    }

    //加入拼团
    joinCollage(id) {
        //-3已参加过三次拼团，不能再次参加 -2已参加过两次拼团，不能再次参加  -1拼团已过期 1参团成功,请开奖  5已参团(重复进入拼团)  10参团人数已满，不能参团了  20拼团已结束
        this.$post('/collage/join', {id}).then(res => {
            if (res.code < 0) {
                wx.showToast({
                    title: res.reason,
                    icon: 'none'
                })
                return wx.redirectTo({
                    url: '/pages/goods/index'
                })
            }
            if (res.collage.winner && res.collage.status == 2) {//如果我是中奖这，并已经支付
                return wx.redirectTo({
                    url: '/pages/goods/index'
                })
            }
            for (let item of res.collage.member) {
                if (item.isMe) {
                    if (item.openPrize && !res.collage.winner) {
                        return wx.redirectTo({
                            url: '/pages/goods/index'
                        })
                    }
                    this.setData({
                        'vo.goodsInfo': res.collage.product,
                        'vo.member': res.collage.member
                    })
                    if (res.collage.winner && res.collage.status === 1 && item.openPrize) {//如果我中奖，未支付
                        this.getAddressInfo()
                        this.setData({
                            'vo.status': 'prize',
                            'vo.showPrize': false,
                            'vo.showWinner': true,
                            'vo.winnerName': item.user.nickName,
                            'vo.winnerAvatar': item.user.avatarUrl,
                            'vo.winnerTime': this.getWinnerTime(item.openPrizeTime)
                        })
                    }
                    break
                }
            }

            if (this.data.vo.status !== 'prize') { //如果没有中奖
                wx.showToast({
                    title: res.reason,
                    icon: 'none'
                })
                let status = res.collage.status
                if (status == 10 || status == 20) {
                    status = -2
                    this.setData({
                        'vo.openPrizeBtn': '发起拼团'
                    })
                }
                this.setPageStatus(status)
            }
        }).catch(err=> {
            wx.showModal({
                title: "错误",
                content: err.message,
                showCancel: false
            })
        })
    }

    //地址管理
    getAddressInfo() {
        this.$post('/address/list').then(res => {
            if (res.length === 0) {
                this.setData({
                    'vo.prizeHandle': '添加地址',
                    'vo.payHandle': '添加地址'
                })
            } else if (res.length > 0) {
                res.map((item, index)=> {
                    if (item.default) {
                        this.setData({
                            'vo.addressName': item.name,
                            'vo.addressPhone': item.mobile,
                            'vo.address': item.province + item.city + item.area + item.address,
                            'vo.prizeHandle': '修改地址',
                            'vo.payHandle': '确认支付',
                            'po.addressId': item._id
                        })
                    }
                })
            }
        }).catch(err=> {
            wx.showModal({
                title: "错误",
                content: err.message,
                showCancel: false
            })
        })
    }

    chooseAddress() {
        wx.chooseAddress({
            success: (res) => {
                let pname = res.provinceName
                if (pname === '新疆' || pname === '西藏' || pname === '内蒙古' || pname === '黑龙江' || pname === '青海') {
                    wx.showModal({
                        title: "提示",
                        content: '暂不支持' + pname + '省的发货，请选择其他地址',
                        showCancel: false
                    })
                    return
                }
                let params = {
                    mobile: res.telNumber,
                    name: res.userName,
                    address: res.detailInfo,
                    province: res.provinceName,
                    city: res.cityName,
                    area: res.countyName
                }
                if (this.data.vo.addressHandle === '点击修改') {
                    Object.assign(params, ...{
                        id: this.data.po.id
                    })
                }
                this.postAddressInfo(params)
            },
            fail: (err)=> {
                if (err.errMsg === 'chooseAddress:cancel') {
                    return
                }
                wx.showToast({
                    title: "授权失败，请在小程序的设置中打开【通讯录地址】权限",
                    icon: 'none'
                })
            }
        })
    }

    updateAddress() {
        let that = this
        wx.getSetting({
            success: (res)=> {
                if (!res.authSetting['scope.address']) {
                    wx.authorize({
                        scope: 'scope.address',
                        success: (res)=> {
                            that.chooseAddress()
                        },
                        fail: (res)=> {
                            wx.openSetting({
                                success: (res)=> {
                                    if (res.authSetting['scope.address']) {
                                        wx.showToast({
                                            title: "授权成功",
                                            icon: 'none'
                                        })
                                    } else {
                                        wx.showToast({
                                            title: "授权失败，请打开'通讯录地址'",
                                            icon: 'none'
                                        })
                                    }

                                },
                                fail: (res)=> {
                                    wx.showToast({
                                        title: "授权失败，请重试",
                                        icon: 'none'
                                    })
                                }
                            })
                        }
                    })
                }
                that.chooseAddress()
            }
        })
    }

    postAddressInfo(params) {
        this.$post('/address/edit', params).then(res=> {
            this.getAddressInfo()
            this.setData({
                'vo.prizeHandle': '修改地址',
                'vo.payHandle': '确认支付'
            })
        }).catch(err=> {
            wx.showModal({
                title: "错误",
                content: err.message,
                showCancel: false
            })
        })
    }


    startPay() {
        let that = this
        if (this.data.vo.payHandle === '添加地址') {
            this.updateAddress()
            return
        }
        if (this.data.vo.payHandle === '已完成支付') {
            return
        }
        this.$post('/order/preOrder', {
            collageId: this.data.po.joinId,
            addressId: this.data.po.addressId
        }).then(res=> {
            wx.requestPayment({
                'timeStamp': res.timeStamp,
                'nonceStr': res.nonce_str,
                'package': 'prepay_id=' + res.prepay_id,
                'signType': 'MD5',
                'paySign': res.paySign,
                'success': function (res) {
                    that.setData({
                        'vo.payHandle': '已完成支付'
                    })
                    wx.showModal({
                        content: '支付成功',
                        showCancel: false,
                        success: function () {
                            wx.navigateTo({
                                url: `/pages/save/index?goodsImg=${that.data.vo.goodsInfo.img[0]}`
                            })
                        }
                    })
                },
                'fail': function (res) {
                    wx.showToast({
                        title: '支付失败，请重试',
                        icon: 'none'
                    })
                }
            })
        })
    }
}